package com.zzj.hotel.basedao;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;



public abstract class HibernateBaseDao<T> implements BaseDao<T> {

	/**
	 * 获取需要操作的实体类class
	 * 
	 * @return
	 */
	public abstract Class<T> getEntityClass();

	public abstract String getIdProName();

	/**
	 * spring mongodb　集成操作类　
	 */
	protected HibernateTemplate hibernateTemplate;

	/**
	 * 注入mongodbTemplate
	 * 
	 * @param hibernateTemplate
	 */
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	/**
	 * 通过一定的条件查询一个实体
	 * 
	 * @param query
	 * @return
	 */
	public T selectOne(Map<String, Object> queryMap) {
		/*Query query = MongoUtil.getQuery(queryMap);

		return hibernateTemplate.findOne(query, this.getEntityClass());
		 */
		DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
		HibernateUtil.getCriterion(criteria, queryMap);
		List<T> resList = hibernateTemplate.findByCriteria(criteria, 0, 1);
		if (resList != null && resList.size()>0)
			return resList.get(0);

		return null;
	}

	/**
	 * 通过ID获取记录
	 * 
	 * @param id
	 * @return
	 */
	public T selectById(String id) {

		return hibernateTemplate.get(this.getEntityClass(), id);

	}

	/**
	 * 通过id删除对象
	 * 
	 * @see com.foxit.userspace.mongo.dao.BaseDao#deleteById(java.lang.String)
	 */
	public void deleteById(String id) {


		if (id == null) {
			return;
		}
		Object entity = selectById( id);
		if (entity == null) {
			return;
		}
		delete(entity);
	}

	/**
	 * 通过条件删除实体(集合)
	 * 
	 * @param query
	 */
	public void delete(Map<String, Object> queryMap) {

		List<T> list = this.selectList(queryMap);
		hibernateTemplate.deleteAll(list);

		/*
		Query query = MongoUtil.getQuery(queryMap);
		hibernateTemplate.remove(query, getEntityClass());
		 */
		//hibernateTemplate.execute(action)
		/*hibernateTemplate.execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException,
			SQLException {
			return session.createQuery(hql).
			}
			});
		 */
	}

	/**
	 * 通过条件查询实体(集合)
	 * 
	 * @param query
	 */
	public List<T> selectList(Map<String, Object> queryMap) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
		if(queryMap != null)
			HibernateUtil.getCriterion(criteria, queryMap);
		return  hibernateTemplate.findByCriteria(criteria);
	}


	/**
	 * 保存一个对象到mongodb
	 * 
	 * @param bean
	 * @return
	 */
	public void save(T bean) {
		hibernateTemplate.save(bean);
	}

	public void insert(T bean) {
		hibernateTemplate.save(bean);
	}

	public void insertList(List<T> beans) {
		hibernateTemplate.saveOrUpdateAll(beans);
	}

	public void delete(Object... entities) {
		for (Object entity : entities) {
			if (entity != null) {
				hibernateTemplate.delete(entity);
			}
		}
	}
	public void update(Object entity){
		hibernateTemplate.update(entity);
	}
}